﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NationalInstruments.VisaNS;
using System.Windows.Forms;

namespace SimpleTestFrameForNFC
{
    class BaseInstrument
    {
        private MessageBasedSession messageBasedSession;

        public void Connect(string addr)
        {
            object[] attributes = this.GetType().GetCustomAttributes(typeof(InstrumentInterfaceTypeAnno), false);
            if (attributes.Length > 0)
            {
                InstrumentInterfaceTypeAnno anno = (InstrumentInterfaceTypeAnno)attributes[0];
                string resourceName = string.Empty;
                if (anno.type == InstrumentInterfaceType.GPIB)
                {
                    resourceName = "GPIB0::" + addr + "::INSTR";
                }
                else if (anno.type == InstrumentInterfaceType.Serial)
                {
                    resourceName = "ASRL" + addr + "::INSTR";
                }
                else if (anno.type == InstrumentInterfaceType.USB)
                {
                    //USB0::<Vendor ID>::<Product ID>::<Serial Number>::INSTR
                    string[] vs = addr.Split(':');
                    resourceName = "USB0::" + vs[0] + "::" + vs[1] + "::" + vs[2] + "::INSTR";
                }
                else if (anno.type == InstrumentInterfaceType.Ethernet)
                {
                    //TCPIP0::<IP Address>::<Port>::SOCKET
                    string[] vs = addr.Split(':');
                    resourceName = "TCPIP0::" + vs[0] + "::" + vs[1] + "::SOCKET";
                }
                else
                {
                    throw new Exception(this.GetType().FullName + "注解InstrumentInterfaceTypeAnno属性type必须是InstrumentInterfaceType中的一个");
                }

                messageBasedSession = (MessageBasedSession)ResourceManager.GetLocalManager().Open(resourceName, AccessModes.NoLock, 1000);
                try
                {
                    string response = messageBasedSession.Query("*IDN?");
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.StackTrace);
                    MessageBox.Show("设备：" + this.GetType().Name + "连接失败，Address：" + addr, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    messageBasedSession = null;
                }
            }
            else
            {
                throw new Exception(this.GetType().FullName + "未设置注解InstrumentInterfaceTypeAnno");
            }
        }

        public void Write(string cmd)
        {
            if (messageBasedSession == null)
            {
                return;
            }
            messageBasedSession.Write(cmd);
        }

        public string Query(string cmd)
        {
            if (messageBasedSession == null)
            {
                return null;
            }
            return messageBasedSession.Query(cmd);
        }
    }
}
